var camera, scene, renderer, stats;
var materials = [];
var currentMaterialIndex = 0;
var geometry, mesh;

function init() {
	divWidth = 800;
	height = 600;
	camera = new THREE.PerspectiveCamera(75, divWidth
			/ height, 1, 10000);
	camera.position.y = 1000;
	camera.lookAt( new THREE.Vector3(0,0,0) );
	scene = new THREE.Scene();

	geometry = new THREE.CubeGeometry(200, 200, 200);
	geometry.dynamic = true;
	
	materials.push(new THREE.MeshBasicMaterial({
		color : 0xff0000,
		wireframe : true
	}));
	materials.push(new THREE.MeshBasicMaterial({
		color : 0x000000,
		wireframe : true
	}));

	mesh = new THREE.Mesh(geometry, materials[currentMaterialIndex]);
	scene.add(mesh);

	ground = new THREE.Mesh( new THREE.PlaneGeometry( 1000, 1000, 10, 10 ), materials[0] );
	ground.position.y = -100;
	ground.rotation.x = - Math.PI / 2;
	ground.receiveShadow = true;
	scene.add( ground );
	
	renderer = new THREE.WebGLRenderer();
	renderer.setSize(divWidth, height);

	document.getElementById("webGL").appendChild(renderer.domElement);

	stats = new Stats();
	stats.domElement.style.position = 'absolute';
	stats.domElement.style.top = '200px';
	document.getElementById('webGL').appendChild( stats.domElement );
}

function animate() {

	// note: three.js includes requestAnimationFrame shim
	requestAnimationFrame(animate);

	mesh.rotation.x += 0.01;
	mesh.rotation.y += 0.02;

	renderer.render(scene, camera);
	stats.update();
}

jQuery(function($) {

	Wicket.Event.subscribe("/websocket/open", function(jqEvent, message) {
		console.log("Connection opened.");
		Wicket.WebSocket.send("Message from client to server.");
	});
	Wicket.Event.subscribe("/websocket/message", function(jqEvent, message) {
		console.log("I got message: " + message);
		if(message == "changeColor") {
			currentMaterialIndex++;
			if(currentMaterialIndex > 1) {
				currentMaterialIndex = 0;
			}
			mesh.material = materials[currentMaterialIndex];
		}
	});

	init();
	animate();
});
